package handler

import (
	"context"
	"errors"
	"fmt"
	"gowork/studentGrpc/model"
	"gowork/studentGrpc/webMessage"
	"gowork/studentGrpc/webServer/service"
)

//学生服务管理实现
type StudentHandlerCuda struct {
	Sip *service.StudentSriImp
	Tag string
}

//新增学生的服务接口实现
func (sh *StudentHandlerCuda) InsertStudent(ctx context.Context, request *webMessage.AddUpStudent) (*webMessage.State, error) {

	//time.Sleep(time.Second*3)

	if request.Id == "" || request.Name == "" || request.Birth == "" || request.Sex == ""{
		return nil, errors.New(" 请求参数不能为空,请重新请求。")
	}
	var ms = model.Student{
		Id:request.Id,
		Name:request.Name,
		Birth:request.Birth,
		Sex:request.Sex,
	}

	var response = &webMessage.State{}
	receive := sh.Sip.InesrtSri(&ms)
	if receive["code"] == "200"{
		response.Message = receive["message"]
		response.Code = receive["code"]
		return response ,nil
	}else{
		return nil, errors.New("插入失败")
	}
	
}

//删除学生的服务接口实现
func (sh *StudentHandlerCuda) DeleteStudent(ctx context.Context, request *webMessage.DelStudent) (*webMessage.State, error) {

	if request.Name == ""{
		return nil, errors.New(" 请求参数不能为空,请重新请求。")
	}

	var response = &webMessage.State{}
	receive := sh.Sip.DeleteSri(request.Name)
	if receive["code"] == "200"{
		response.Message = receive["message"]
		response.Code = receive["code"]
		return response ,nil
	}else{
		return nil, errors.New("删除失败")
	}
	
}

//修改学生的服务接口实现
func (sh *StudentHandlerCuda) UpdateStudent(ctx context.Context, request *webMessage.AddUpStudent) (*webMessage.State, error) {

	if request.Id == "" || request.Name == "" || request.Birth == "" || request.Sex == ""{
		return nil, errors.New(" 请求参数不能为空,请重新请求。")
	}

	var ms = model.Student{
		Id:request.Id,
		Name:request.Name,
		Birth:request.Birth,
		Sex:request.Sex,
	}

	var response = &webMessage.State{}
	receive := sh.Sip.UpdateSri(&ms)
	if receive["code"] == "200"{
		response.Message = receive["message"]
		response.Code = receive["code"]
		return response, nil
	}else{
		return nil, errors.New("更新失败")
	}
	
}

//查询学生的服务接口实现
func (sh *StudentHandlerCuda) QueryStudent(ctx context.Context, request *webMessage.List) (*webMessage.StudentListResponse, error) {
	var t = service.StudentSriImp{}
	sh.Sip = &t
	receive := sh.Sip.QuerySri()
	fmt.Println(receive)

	var response = &webMessage.StudentListResponse{}
	for _, v := range receive{
		var qsr = webMessage.QueStudentResponse{
			Id:v.Id,
			Name:v.Name+"From"+sh.Tag,
			Birth:v.Birth,
			Sex:v.Sex,
		}
		response.StudentList = append(response.StudentList, &qsr)
	}
	return response, nil
}

// Handler(){
// 	return StudentHandlerCuda{}
// }